package com.spinach.game.events.impl;

import com.alibaba.fastjson2.JSONObject;
import com.spinach.game.config.DouDiZhuConfig;
import com.spinach.game.core.GameMessage;
import com.spinach.game.core.GamePlayer;
import com.spinach.game.core.Room;
import com.spinach.game.core.UserInfo;
import com.spinach.game.enums.ClientEventCode;
import com.spinach.game.enums.RoomStatus;
import com.spinach.game.enums.ServerEventCode;
import com.spinach.game.events.ServerEvent;
import com.spinach.game.events.data.client.JoinRoomClientData;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class JoinRoomServerEvent implements ServerEvent {
    @Autowired
    private DouDiZhuConfig douDiZhuConfig;

    @Override
    public ServerEventCode getEventCode() {
        return ServerEventCode.CODE_ROOM_JOIN;
    }

    @Override
    public void consumer(Channel channel, GameMessage message) {
        Long userId = message.getUserId();
        UserInfo user = douDiZhuConfig.getUser(userId);
        Long roomId = message.getRoomId();
        Room room = douDiZhuConfig.getRoom(roomId);

        //加入房间
        addGamePlayer(channel, room, user);
        //设置房间状态为等待
        room.setRoomStatus(RoomStatus.WAIT);

        List<GamePlayer> players = room.getPlayers();
        //发送玩家加入信息
        for (GamePlayer player : players) {
            Channel ch = player.getChannel();
            JoinRoomClientData joinRoomClientData = JoinRoomClientData.builder().build();
            joinRoomClientData.setRoomId(roomId);

            if (ch.equals(channel)) {
                //通知自己上下家信息
                joinRoomClientData.setNext(player.getNext().getUser());
                joinRoomClientData.setPre(player.getPre().getUser());
            } else {
                GamePlayer nextPlayer = player.getNext();
                GamePlayer prePlayer = player.getPre();
                if (player.equals(nextPlayer)) {
                    //通知下家加入的玩家信息
                    joinRoomClientData.setNext(user);
                }
                if (player.equals(prePlayer)) {
                    //通知上家加入的玩家信息
                    joinRoomClientData.setPre(user);
                }
            }
            //消息发送
            GameMessage produceMessage = GameMessage.builder()
                    //客户端事件名称
                    .code(ClientEventCode.CODE_ROOM_JOIN.name())
                    //返回不存在的房间id
                    .data(joinRoomClientData)
                    .build();
            ch.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(produceMessage)));
        }
    }

    /**
     * 加入房间
     *
     * @param channel
     * @param room
     * @param user
     */
    private void addGamePlayer(Channel channel, Room room, UserInfo user) {
        GamePlayer gamePlayer = GamePlayer.builder()
                .roomId(room.getId())
                .user(user)
                .channel(channel)
                .build();

        room.getChannelGamePlayerMap().put(channel, gamePlayer);

        //加入房间
        List<GamePlayer> players = room.getPlayers();
        players.add(gamePlayer);
        int playerNum = room.getPlayerNum().incrementAndGet();
        GamePlayer head = room.getHead();
        GamePlayer tail = room.getTail();
        if (head == null) {
            head = gamePlayer;
        }
        if (tail != null) {
            tail.setNext(gamePlayer);
            gamePlayer.setPre(tail);
        }
        tail = gamePlayer;
        if (playerNum == 3) {
            tail.setNext(head);
            head.setPre(tail);
        }
    }
}
